package cn.jietuo.juc.c_010_interview3;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/11
 * @description:
 */
public class T02_ReentrantLock {

    static char[] str1 = new char[]{'1', '2', '3', '4', '5', '6', '7', '8'};
    static char[] str2 = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};

    static CountDownLatch countDownLatch = new CountDownLatch(1);

    static Thread t1 = null, t2 = null;


    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();
        t1 = new Thread(() -> {
            try {
                lock.lock();
                for (int i = 0; i < str1.length; i++) {
                    System.out.println(str1[i]);
                    countDownLatch.countDown();
                    condition2.signal();
                    condition1.await();
                }
                condition2.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });


        t2 = new Thread(() -> {
            try {
                countDownLatch.await();
                lock.lock();
                for (int i = 0; i < str2.length; i++) {
                    condition1.signal();
                    System.out.println(str2[i]);
                    condition2.await();
                }
                condition1.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });
        t2.start();
        t1.start();
    }

}
